package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entity.CommonResult;
import com.atguigu.springcloud.entity.Payment;
import com.atguigu.springcloud.service.PaymentService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;
    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment){
        log.info("插入数据payment  {}  ",payment);
        int res= paymentService.create(payment);
        log.info("创建结果{}  ",res);
        return res>0 ? new CommonResult(200,"添加成功,serverPort: "+serverPort,res) : new CommonResult(444,"插入失败,serverPort: "+serverPort,null);
    }
    @GetMapping("/payment/get/{id}")
    public CommonResult create(@PathVariable Long id){

        Payment payment = paymentService.getPaymentById(id);
        log.info("查询结果{} ",payment);
        return payment!=null ? new CommonResult(200,"查询成功,serverPort: "+serverPort,payment) : new CommonResult(200,"查询失败,serverPort: "+serverPort,null);
    }
    @GetMapping("/payment/lb/{id}")
    public String lib(@PathVariable Long id){

        return serverPort;
    }

    @GetMapping("/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("-----service----{}",service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
//            System.out.println(instance.toString());
            log.info(instance.getInstanceId()+"\t"+instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }
    @GetMapping(value = "/payment/feign/timeout")
    public String paymentFeignTimeout() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            log.info("/payment/feign/timeout {}",serverPort);
            return serverPort;
        }
    }

    @GetMapping(value="/payment/zipkin")
    public String paymentZipkin() {
        return "hello,i am paymentZipkin server fallback,O(∩_∩)O哈哈~";
    }

}
